package com.example.hello.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * @maker twc
 * @ time 2021/4/21 11:35
 */
public class OnClicView extends View {
    public static final String TAG = OnClicView.class.getSimpleName();
    private static  final int FLUSH_VIEW = 100;
    //画笔
    private             Paint  mPaint;
    //圆心X,Y
    private             int    cx, cy;
    private int strokeWidth;
    private int radius;

    //子线程
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FLUSH_VIEW:
                    //刷新
                    flush();
                    //重绘
                    invalidate();
                    if (mPaint.getAlpha()!=0){
                        handler.sendEmptyMessageDelayed(FLUSH_VIEW,100);
                    }
                    break;
            }
        }
    };


    public OnClicView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mPaint = new Paint();
        //抗锯齿
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.RED);
        //空心
        mPaint.setStyle(Paint.Style.STROKE);
        //设置内院宽度
        mPaint.setStrokeWidth(strokeWidth);
        mPaint.setAlpha(255);

        strokeWidth = 0;
        radius = 0;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(cx, cy, radius, mPaint);
    }

    //触摸事件
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                cx = (int) event.getX();
                cy = (int) event.getY();
                Log.i(TAG, "中心点坐标" + cx + "," + cy);
                break;

        }
        init();
        handler.sendEmptyMessage(FLUSH_VIEW);
        return true;
    }
    //刷新状态
    private void flush(){
        radius += 10;
        strokeWidth = radius / 4 ;
        mPaint.setStrokeWidth(strokeWidth);
        int endAlpha = mPaint.getAlpha()-20;
        if(endAlpha<20){
            endAlpha = 0;
        }
        mPaint.setAlpha(endAlpha);
    }
}
